const dubboProjectModel = require('../models/dubboProject.js');
const yapi = require('../yapi.js');
// const _ = require('underscore');
const baseController = require('./base.js');
const interfaceModel = require('../models/interface.js');
const interfaceColModel = require('../models/interfaceCol.js');
const caseColModel = require('../models/caseCol');
const interfaceCaseModel = require('../models/interfaceCase.js');
const interfaceCatModel = require('../models/interfaceCat.js');
const groupModel = require('../models/group');
const commons = require('../utils/commons.js');
const userModel = require('../models/user.js');
const logModel = require('../models/log.js');
const followModel = require('../models/follow.js');
const tokenModel = require('../models/token.js');
// const url = require('url');
const {getToken} = require('../utils/token');
const sha = require('sha.js');

class dubboProjectController extends baseController {
  constructor(ctx) {
    super(ctx);
    this.Model = yapi.getInst(dubboProjectModel);
    this.groupModel = yapi.getInst(groupModel);
    this.logModel = yapi.getInst(logModel);
    this.followModel = yapi.getInst(followModel);
    this.tokenModel = yapi.getInst(tokenModel);
    this.interfaceModel = yapi.getInst(interfaceModel);
    this.caseColModel = yapi.getInst(caseColModel);

    // const id = 'number';
    // const member_uid = ['number'];
    // const cnname = {
    //   type: 'string',
    //   minLength: 1
    // };
    // const enname = {
    //  type: 'string',
    //  minLength: 1
    // };
    // const role = {
    //   type: 'string',
    //   enum: ['owner', 'dev', 'guest']
    // };
    // const group_id = 'number';
    // const desc = 'string';
    // const icon = 'string';
    // const color = 'string';
    // const onlinedate = 'string';
    // const dgroup = 'string';
  }
  verifyDomain(domain) {
    if (!domain) {
      return false;
    }
    if (/^[a-zA-Z0-9\-_\.]+?\.[a-zA-Z0-9\-_\.]*?[a-zA-Z]{2,6}$/.test(domain)) {
      return true;
    }
    return false;
  }

  /**
   * 判断分组名称是否重复
   * @interface /project/check_project_name
   * @method get
   */

  async checkProjectName(ctx) {
    try {
      let cnname = ctx.request.query.cnname;
      let groupid = ctx.request.query.group_id;

      if (!cnname) {
        return (ctx.body = yapi.commons.resReturn(null, 401, '项目名不能为空'));
      }
      let checkRepeat = await this.Model.checkNameRepeat(cnname, groupid);

      if (checkRepeat > 0) {
        return (ctx.body = yapi.commons.resReturn(null, 401, '已存在的项目名'));
      }

      ctx.body = yapi.commons.resReturn({});
    } catch (err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

  /**
   * 添加项目分组
   * @interface /dubboproject/add
   * @method POST
   * @category dubboProject
   * @foldnumber 10
   * @param {String} cnname 项目名称，不能为空
   * @param {String} enname 项目简称，不能为空
   * @param {Number} groupid 项目分组id，不能为空
   * @param {String} dgroup DUBBO分组名称，不能为空
   * @param  {String} [desc] 项目描述
   * @returns {Object}
   */
  async add(ctx) {
    let params = ctx.params;
    if ((await this.checkAuth(params.group_id, 'group', 'edit')) !== true) {
      return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
    }

    let checkRepeat = await this.Model.checkNameRepeat(params.cnname, params.group_id);

    if (checkRepeat > 0) {
      return (ctx.body = yapi.commons.resReturn(null, 401, '已存在的项目名'));
    }

    let data = {
      //页面数据
      cnname: params.cnname,
      enname: params.enname,
      desc: params.desc,
      groupid: params.group_id,
      dgroup: params.dgroup,
      icon: params.icon,
      color: params.color,
      onlinedate: params.onlinedate,
      //ttc：新增字段expname和childbase
      expname:params.expname,
      childbase:params.childbase,
      //默认数据 后台设置
      cuserid: this.getUid(),
      euserid:this.getUid(),
      ctime: yapi.commons.time(),
      etime: yapi.commons.time(),
      userlist: [],
      projecttype: 'private',
      status: 1,
      batch: 0,
      evnconfig: [{ cname: 'local', dubbourl: 'http://127.0.0.1' }]
    };

    let result = await this.Model.save(data);
    let colInst = await yapi.getInst(caseColModel);
    if (result._id) {
      await colInst.save({
        name: '公共测试集',
        projectid: result._id,
        desc: '公共测试集',
        uid: this.getUid(),
        add_time: yapi.commons.time(),
        up_time: yapi.commons.time()
      });
    }

    // 20190905 9:48 wms 记录操作
    let uid = this.getUid();
    let username = this.getUsername();
    yapi.commons.saveLog({
      content: `<a href="/user/profile/${this.getUid()}">${username}</a> 添加了Dubbo项目 <a href="/dubboproject/${
          result._id
      }">${params.cnname}</a>`,
      type: 'dubboproject',
      uid,
      username: username,
      typeid: result._id
    });
    ctx.body = yapi.commons.resReturn(result);
  }

  /**
   * 添加项目成员
   * @interface /dubboproject/add_member
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {Array} member_uid 项目成员uid,不能为空
   * @returns {Object}
   * @example ./api/dubboproject/add_member.json
   */
  async addMember(ctx) {
    try{
      let params = ctx.params;
      if ((await this.checkAuth(params.id, 'dubboproject', 'edit')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      let add_members = [];
      let exist_members = [];
      let no_members = [];
      for (let i = 0, len = params.member_uids.length; i < len; i++) {
        let id = params.member_uids[i];
        let check = await this.Model.checkMemberRepeat(params.id, id);
        let userdata = await yapi.commons.getMemberdata(id, params.role);
        if (check > 0) {
          exist_members.push(userdata);
        } else if (!userdata) {
          no_members.push(id);
        } else {
          add_members.push(userdata);
        }
      }

      let result = await this.Model.addMember(params.id, add_members);
      if (add_members.length) {
        let members = add_members.map(item => {
          return `<a href = "/user/profile/${item.userid}">${item.username}</a>`;
        });
        members = members.join('、');
        let username = this.getUsername();
        yapi.commons.saveLog({
          content: `<a href="/user/profile/${this.getUid()}">${username}</a> 添加了项目成员 ${members}`,
          type: 'dubboproject',
          uid: this.getUid(),
          username: username,
          typeid: params.id
        });
      }
      ctx.body = yapi.commons.resReturn({
        result,
        add_members,
        exist_members,
        no_members
      });
    } catch(err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }
  /**
   * 删除项目成员
   * @interface /dubboproject/del_member
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {member_uid} uid 项目成员uid,不能为空
   * @returns {Object}
   * @example ./api/dubboproject/del_member.json
   */

  async delMember(ctx) {
    try {
      let params = ctx.params;

      var check = await this.Model.checkMemberRepeat(params.id, params.member_uid);
      if (check === 0) {
        return (ctx.body = yapi.commons.resReturn(null, 400, '项目成员不存在'));
      }

      if ((await this.checkAuth(params.id, 'project', 'danger')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      let result = await this.Model.delMember(params.id, params.member_uid);
      let username = this.getUsername();
      yapi
        .getInst(userModel)
        .findById(params.member_uid)
        .then(member => {
          yapi.commons.saveLog({
            content: `<a href="/user/profile/${this.getUid()}">${username}</a> 删除了项目中的成员 <a href="/user/profile/${
              params.member_uid
            }">${member ? member.username : ''}</a>`,
            type: 'dubboproject',
            uid: this.getUid(),
            username: username,
            typeid: params.id
          });
        });
      ctx.body = yapi.commons.resReturn(result);
    } catch (e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
  }

  /**
   * 获取项目成员列表
   * @interface /dubboproject/get_member_list
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @return {Object}
   * @example ./api/dubboproject/get_member_list.json
   */

  async getMemberList(ctx) {
    let params = ctx.params;
    if (!params.id) {
      return (ctx.body = yapi.commons.resReturn(null, 400, '项目id不能为空'));
    }

    try{
      let project = await this.Model.get(params.id);
      let userlist = project.userlist;
      ctx.body = yapi.commons.resReturn(userlist);
    } catch(e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
  }

  /**
   * 获取项目信息
   * @interface /dubboproject/get
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @returns {Object}
   * @example ./api/dubboproject/get.json
   */

  async get(ctx) {
    try {
      let params = ctx.params;
      let projectId= params.id || params.project_id || params.projectid; // 通过 token 访问
      let result = await this.Model.getBaseInfo(projectId);
      if (!result) {
        return (ctx.body = yapi.commons.resReturn(null, 400, '不存在的项目'));
      }
      if (result.project_type === 'private') {
        if ((await this.checkAuth(result._id, 'dubboproject', 'view')) !== true) {
          return (ctx.body = yapi.commons.resReturn(null, 406, '没有权限'));
        }
      }
      result = result.toObject();
      let catInst = yapi.getInst(interfaceCatModel);
      let cat = await catInst.list(params.id);
      result.cat = cat;
      result.role = await this.getProjectRole(params.id, 'dubboproject');

      // let group = await this.groupModel.get(params.id);
      // console.log('dubboPorject的get的group');
      // console.log(group);
      // result.userList = group.members;

      yapi.emitHook('project_get', result).then();
      ctx.body = yapi.commons.resReturn(result);
    } catch(err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

  /**
   * 获取项目列表
   * @interface /dubboproject/list
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} group_id 项目group_id，不能为空
   * @returns {Object}
   * @example ./api/dubboproject/list.json
   */

  async list(ctx) {
    try{
      let group_id = ctx.params.group_id;
      let result = await this.Model.list(group_id);
      let newResult = [];
      let auth = await this.checkAuth(group_id, 'group', 'view')
      for (let index = 0, item, r = 1; index < result.length; index++) {
        item = result[index].toObject();
        if (item.projecttype === 'private' && auth === false) {
          r = await this.Model.checkMemberRepeat(item._id, this.getUid());
          if (r === 0) {
            continue;
          }
        }
        newResult.push(item);
      }
      ctx.body = yapi.commons.resReturn({
        list: newResult
      });

    } catch(err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }

  }

  /**
   * 删除项目
   * @interface /dubboproject/del
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @returns {Object}
   * @example ./api/dubboproject/del.json
   */

  async del(ctx) {
    try{
      let id = ctx.params.id;

      if ((await this.checkAuth(id, 'dubboproject', 'danger')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      let interfaceInst = yapi.getInst(interfaceModel);
      let interfaceColInst = yapi.getInst(interfaceColModel);
      let interfaceCaseInst = yapi.getInst(interfaceCaseModel);
      await interfaceInst.delByProjectId(id);
      await interfaceCaseInst.delByProjectId(id);
      await interfaceColInst.delByProjectId(id);
      yapi.emitHook('project_del', id).then();
      let result = await this.Model.del(id);
      ctx.body = yapi.commons.resReturn(result);
    } catch (err){
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

  /**
   * 修改项目成员角色
   * @interface /dubboproject/change_member_role
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {String} id 项目id
   * @param {String} member_uid 项目成员uid
   * @param {String} role 权限 ['owner'|'dev']
   * @returns {Object}
   * @example
   */
  async changeMemberRole(ctx) {
    try{
      let params = ctx.request.body;
      let projectInst = yapi.getInst(dubboProjectModel);

      var check = await projectInst.checkMemberRepeat(params.id, params.member_uid);
      if (check === 0) {
        return (ctx.body = yapi.commons.resReturn(null, 400, '项目成员不存在'));
      }
      if ((await this.checkAuth(params.id, 'dubboproject', 'danger')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      let rolename = {
        0: '组长',
        1: '开发者',
        2: '访客'
      };

      let result = await projectInst.changeMemberRole(params.id, params.member_uid, params.role);

      let username = this.getUsername();
      yapi
        .getInst(userModel)
        .findById(params.member_uid)
        .then(member => {
          yapi.commons.saveLog({
            content: `<a href="/user/profile/${this.getUid()}">${username}</a> 修改了项目中的成员 <a href="/user/profile/${
              params.member_uid
            }">${member.username}</a> 的角色为 "${rolename[params.role]}"`,
            type: 'dubboproject',
            uid: this.getUid(),
            username: username,
            typeid: params.id
          });
        });
      ctx.body = yapi.commons.resReturn(result);
    } catch(err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

  /**
   * 项目头像设置
   * @interface /dubboproject/upset
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {String} icon 项目icon
   * @param {Array} color 项目color
   * @returns {Object}
   * @example ./api/dubboproject/upset
   */
  async upSet(ctx) {
    let id = ctx.request.body.id;
    let data = {};
    if ((await this.checkAuth(id, 'dubboproject', 'danger')) !== true) {
      return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
    }
    data.color = ctx.request.body.color;
    data.icon = ctx.request.body.icon;
    if (!id) {
      return (ctx.body = yapi.commons.resReturn(null, 405, '项目id不能为空'));
    }
    try {
      let result = await this.Model.up(id, data);
      ctx.body = yapi.commons.resReturn(result);
    } catch (e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
    try {
      this.followModel.updateById(this.getUid(), id, data).then(() => {
        let username = this.getUsername();
        yapi.commons.saveLog({
          content: `<a href="/user/profile/${this.getUid()}">${username}</a> 修改了项目图标、颜色`,
          type: 'dubboproject',
          uid: this.getUid(),
          username: username,
          typeid: id
        });
      });
    } catch (e) {
      yapi.commons.log(e, 'error'); // eslint-disable-line
    }
  }

  /**
   * 编辑项目
   * @interface /dubboproject/up
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {String} name 项目名称，不能为空
   * @param {String} basepath 项目基本路径，不能为空
   * @param {String} [desc] 项目描述
   * @returns {Object}
   * @example ./api/dubboproject/up.json
   */
  async up(ctx) {
    try {
      let id = ctx.request.body.id;
      let params = ctx.request.body;

      params = yapi.commons.handleParams(params, {
        name: 'string',
        basepath: 'string',
        group_id: 'number',
        desc: 'string',
        pre_script: 'string',
        after_script: 'string',
        project_mock_script: 'string'
      });

      if (!id) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '项目id不能为空'));
      }

      if ((await this.checkAuth(id, 'dubboproject', 'danger')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      let projectData = await this.Model.get(id);

      if (params.basepath) {
        if ((params.basepath = this.handleBasepath(params.basepath)) === false) {
          return (ctx.body = yapi.commons.resReturn(null, 401, 'basepath格式有误'));
        }
      }

      if (projectData.name === params.name) {
        delete params.name;
      }

      if (params.name) {
        let checkRepeat = await this.Model.checkNameRepeat(params.name, params.group_id);
        if (checkRepeat > 0) {
          return (ctx.body = yapi.commons.resReturn(null, 401, '已存在的项目名'));
        }
      }

      let data = {
        up_time: yapi.commons.time()
      };

      data = Object.assign({}, data, params);

      let result = await this.Model.up(id, data);
      let username = this.getUsername();
      yapi.commons.saveLog({
        content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更新了项目 <a href="/dubbo-project/${id}/interface/api">${
          projectData.cnname
        }</a>`,
        type: 'dubboproject',
        uid: this.getUid(),
        username: username,
        typeid: id
      });
      yapi.emitHook('project_up', result).then();
      ctx.body = yapi.commons.resReturn(result);
    } catch (e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
  }

  /**
   * 编辑项目
   * @interface /dubboproject/up_env
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {Array} [env] 项目环境配置
   * @param {String} [env[].cname] 环境名称
   * @param {String} [env[].dubbourl] 环境域名
   * @param {Array}  [env[].header] header
   * @returns {Object}
   * @example
   */
  async upEnv(ctx) {
    try {
      let id = ctx.request.body.id;
      let params = ctx.request.body;
      if (!id) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '项目id不能为空'));
      }

      if ((await this.checkAuth(id, 'dubboproject', 'edit')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      if (!params.evnconfig || !Array.isArray(params.evnconfig)) {
        return (ctx.body = yapi.commons.resReturn(null, 405, 'evnconfig参数格式有误'));
      }

      let projectData = await this.Model.get(id);
      let data = {
        up_time: yapi.commons.time()
      };

      data.evnconfig = params.evnconfig;
      let isRepeat = this.arrRepeat(data.evnconfig, 'cname');
      if (isRepeat) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '环境变量名重复'));
      }
      let result = await this.Model.up(id, data);
      let username = this.getUsername();
      yapi.commons.saveLog({
        content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更新了项目 <a href="/dubbo-project/${id}/interface/api">${
          projectData.cnname
        }</a> 的环境`,
        type: 'dubboproject',
        uid: this.getUid(),
        username: username,
        typeid: id
      });
      ctx.body = yapi.commons.resReturn(result);
    } catch (e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
  }


    /**
     * 编辑项目
     * @interface /dubboproject/up_add
     * @method POST
     * @category dubboproject
     * @foldnumber 10
     * @param {Number} id 项目id，不能为空
     * @param {Array} [env] 项目环境配置
     * @param {String} [env[].cname] 环境名称
     * @param {String} [env[].dubbourl] 环境域名
     * @returns {Object}
     * @example
     */
    async addEnv(ctx) {
        try {
            let id = ctx.request.body.id;
            let params = ctx.request.body;
            if (!id) {
                return (ctx.body = yapi.commons.resReturn(null, 405, '项目id不能为空'));
            }

            if ((await this.checkAuth(id, 'dubboproject', 'edit')) !== true) {
                return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
            }

            if (!params.evnconfig || !Array.isArray(params.evnconfig)) {
                return (ctx.body = yapi.commons.resReturn(null, 405, 'evnconfig参数格式有误'));
            }

            let projectData = await this.Model.get(id);
            let data = {
                up_time: yapi.commons.time()
            };
            data.evnconfig = params.evnconfig;
            let isRepeat = this.arrRepeat(data.evnconfig, 'cname');
            if (isRepeat) {
                return (ctx.body = yapi.commons.resReturn(null, 405, '环境变量名重复'));
            }
            let result = await this.Model.up(id, data);
            let username = this.getUsername();
            yapi.commons.saveLog({
                content: `<a href="/user/profile/${this.getUid()}">${username}</a> 添加了环境变量 <a href="/dubbo-project/${id}/dubboproject/up_add">${
                    projectData.cnname
                    }</a> 的环境`,
                type: 'dubboproject',
                uid: this.getUid(),
                username: username,
                typeid: id
            });
            ctx.body = yapi.commons.resReturn(result);
        } catch (e) {
            ctx.body = yapi.commons.resReturn(null, 402, e.message);
        }
    }

  /**
   * 编辑项目
   * @interface /dubboproject/up_tag
   * @method POST
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {Array} [tag] 项目tag配置
   * @param {String} [tag[].name] tag名称
   * @param {String} [tag[].desc] tag描述
   * @returns {Object}
   * @example
   */
  async upTag(ctx) {
    try {
      let id = ctx.request.body.id;
      let params = ctx.request.body;
      if (!id) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '项目id不能为空'));
      }

      if ((await this.checkAuth(id, 'dubboproject', 'edit')) !== true) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      }

      if (!params.tag || !Array.isArray(params.tag)) {
        return (ctx.body = yapi.commons.resReturn(null, 405, 'tag参数格式有误'));
      }

      let projectData = await this.Model.get(id);
      let data = {
        up_time: yapi.commons.time()
      };
      data.tag = params.tag;

      let result = await this.Model.up(id, data);
      let username = this.getUsername();
      yapi.commons.saveLog({
        content: `<a href="/user/profile/${this.getUid()}">${username}</a> 更新了项目 <a href="/project/${id}/interface/api">${
          projectData.cnname
        }</a> 的tag`,
        type: 'dubboproject',
        uid: this.getUid(),
        username: username,
        typeid: id
      });
      ctx.body = yapi.commons.resReturn(result);
    } catch (e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
  }

  /**
   * 获取项目的环境变量值
   * @interface /dubboproject/get_env
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空

   * @returns {Object}
   * @example
   */
  async getEnv(ctx) {
    try {
      // console.log(ctx.request.query.project_id)
      let project_id = ctx.request.query.project_id || ctx.request.query.projectid;
      // let params = ctx.request.body;
      if (!project_id) {
        return (ctx.body = yapi.commons.resReturn(null, 405, '项目id不能为空'));
      }

      // 去掉权限判断
      // if ((await this.checkAuth(project_id, 'project', 'edit')) !== true) {
      //   return (ctx.body = yapi.commons.resReturn(null, 405, '没有权限'));
      // }

      let env = await this.Model.getByEnv(project_id);

      ctx.body = yapi.commons.resReturn(env);
    } catch (e) {
      ctx.body = yapi.commons.resReturn(null, 402, e.message);
    }
  }

  arrRepeat(arr, key) {
    const s = new Set();
    arr.forEach(item => s.add(item[key]));
    return s.size !== arr.length;
  }

  /**
   * 获取token数据
   * @interface /dubboproject/token
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {String} q
   * @return {Object}
   */
  async token(ctx) {
    try {
      let project_id = ctx.params.project_id || ctx.params.projectid;
      let data = await this.tokenModel.get(project_id);
      let token;
      if (!data) {
        let passsalt = yapi.commons.randStr();
        token = sha('sha1')
          .update(passsalt)
          .digest('hex')
          .substr(0, 20);

        await this.tokenModel.save({ project_id, token });
      } else {
        token = data.token;
      }

      token = getToken(token, this.getUid())

      ctx.body = yapi.commons.resReturn(token);
    } catch (err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

  /**
   * 更新token数据
   * @interface /dubboproject/update_token
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {Number} id 项目id，不能为空
   * @param {String} q
   * @return {Object}
   */
  async updateToken(ctx) {
    try {
      let project_id = ctx.params.project_id || ctx.params.projectid;
      let data = await this.tokenModel.get(project_id);
      let token, result;
      if (data && data.token) {
        let passsalt = yapi.commons.randStr();
        token = sha('sha1')
          .update(passsalt)
          .digest('hex')
          .substr(0, 20);
        result = await this.tokenModel.up(project_id, token);
        token = getToken(token);
        result.token = token;
      } else {
        ctx.body = yapi.commons.resReturn(null, 402, '没有查到token信息');
      }

      ctx.body = yapi.commons.resReturn(result);
    } catch (err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

  /**
   * 模糊搜索项目名称或者分组名称或接口名称
   * @interface /dubboproject/search
   * @method GET
   * @category dubboproject
   * @foldnumber 10
   * @param {String} q
   * @return {Object}
   * @example ./api/dubboproject/search.json
   */
  async search(ctx) {
    const { q } = ctx.request.query;

    if (!q) {
      return (ctx.body = yapi.commons.resReturn(void 0, 400, 'No keyword.'));
    }

    if (!yapi.commons.validateSearchKeyword(q)) {
      return (ctx.body = yapi.commons.resReturn(void 0, 400, 'Bad query.'));
    }

    let projectList = await this.Model.search(q);
    let groupList = await this.groupModel.search(q);
    let interfaceList = await this.interfaceModel.search(q);

    let projectRules = [
      '_id',
      'name',
      'basepath',
      'uid',
      'env',
      'members',
      { key: 'group_id', alias: 'groupId' },
      { key: 'up_time', alias: 'upTime' },
      { key: 'add_time', alias: 'addTime' }
    ];
    let groupRules = [
      '_id',
      'uid',
      { key: 'group_name', alias: 'groupName' },
      { key: 'group_desc', alias: 'groupDesc' },
      { key: 'add_time', alias: 'addTime' },
      { key: 'up_time', alias: 'upTime' }
    ];
    let interfaceRules = [
      '_id',
      'uid',
      { key: 'title', alias: 'title' },
      { key: 'project_id', alias: 'projectId' },
      { key: 'add_time', alias: 'addTime' },
      { key: 'up_time', alias: 'upTime' }
    ];

    projectList = commons.filterRes(projectList, projectRules);
    groupList = commons.filterRes(groupList, groupRules);
    interfaceList = commons.filterRes(interfaceList, interfaceRules);
    let queryList = {
      project: projectList,
      group: groupList,
      interface: interfaceList
    };

    return (ctx.body = yapi.commons.resReturn(queryList, 0, 'ok'));
  }

  async returnString(ctx) {
    try{
      let string = yapi.WEBCONFIG.exporturl;
      ctx.body = yapi.commons.resReturn({
        string: string
      });
    } catch(err) {
      ctx.body = yapi.commons.resReturn(null, 402, err.message);
    }
  }

}

module.exports = dubboProjectController;
